package Thread.ConsumerAndProducer.method2;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}10:26
 */
public class Test2 {
    private static Integer count = 0;
    private static final Integer FULL = 10;
    //创建冲入锁
    private Lock lock = new ReentrantLock();
    //创建两个条件变量
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();

    Thread producer = new Thread(new Runnable() {
        @Override
        public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    lock.lock();
                    try {
                        while (count == FULL) {
                            try {
                                notFull.await();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            count++;
                            System.out.println(Thread.currentThread().getName() + "生产者生产，目前共有" + count);
                            //唤醒没货的等着的消费者
                            notEmpty.signal();
                        }
                    } finally {
                        lock.unlock();
                    }
                }
        }
    });

    Thread comsumer = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.lock();
                try{
                    while (count==0){
                        try {
                            notEmpty.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        count--;
                        System.out.println(Thread.currentThread().getName()+"消费者消费，目前共有"+count);
                        notFull.signal();
                    }
                }finally {
                    lock.unlock();
                }
            }
        }
    });


    public static void main(String[] args) {
        Test2 test2 = new Test2();
        test2.producer.start();
        test2.comsumer.start();
    }
}
